# -*- coding: utf-8 -*-

"""
@Author: Rwing
@File: UserMiddleware.py
@Time: 2021/12/17 21:25
"""
from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin

from App.models import AXFUsers
from App.views_constant import USER_TOKEN_EXPIRED, USER_NOT_LOGIN

JSON_PATH = (
    "/app/add_cart/"
)

HTTP_PATH = (
    "/app/cart/"
    "/app/mine/"
)


class LoginMiddleware(MiddlewareMixin):

    def process_request(self, request):
        token = request.session.get("token")
        user_id = cache.get(token)
        if request.path in JSON_PATH:
            if user_id:
                try:
                    user = AXFUsers.objects.get(pk=user_id)
                    request.user = user
                except:
                    return JsonResponse(data={"status": USER_TOKEN_EXPIRED, "msg": "用户token已过期"})
            else:
                return JsonResponse(data={"status": USER_NOT_LOGIN, "msg": "用户未登录"})
        elif request.path in HTTP_PATH:
            if user_id:
                try:
                    user = AXFUsers.objects.get(pk=user_id)
                    request.user = user
                except:
                    return redirect(reverse("app:login"))
            else:
                return redirect(reverse("app:login"))
